export type TdictValue = string | number
export type TdictOption = {
	label: string
	value: TdictValue
	[key: string]: any
}
type TdictCache = {
	[key: string]: TdictOption
}
class DictClass {
	public cache: TdictCache = {}
	public strict = true
	public readonly options: TdictOption[] = []
	constructor(options: TdictOption[], strict?: boolean) {
		Object.defineProperty(this, 'options', {
			get() {
				return Array.isArray(options) ? options : []
			},
			configurable: false,
		})
		if (typeof strict == 'boolean') {
			this.strict = false
		}
	}
	get keys() {
		return this.options.map(v => v.value)
	}
	// 根据value获取对应的label
	getLabel(val: TdictValue, defaultVal?: any) {
		if (!Object.hasOwnProperty.call(this.cache, val)) {
			this._fromFor(val)
		}
		if (this.cache[val]) {
			return this.cache[val].label
		}
		if (typeof defaultVal == 'string') {
			return defaultVal
		}
		return val
	}

	// 根据value获取所在item
	getItem(val: TdictValue) {
		if (!Object.hasOwnProperty.call(this.cache, val)) {
			this._fromFor(val)
		}
		return this.cache[val]
	}
	protected _isFinded(val: TdictValue, value: TdictValue) {
		// 严格相等
		if (this.strict) {
			return val === value
		}
		return val == value
	}
	protected _fromFor(val: TdictValue) {
		let result = null
		for (const item of this.options) {
			if (this._isFinded(val, item.value)) {
				result = item
				break
			}
		}
		if (result) {
			this.cache[val] = Object.freeze(result)
		}
	}
}
export { DictClass }
export default DictClass
